import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

import {Storage} from '../utils/storage';
import {Observable} from "rxjs";
import {SERVER_PATH, TOKEN} from "../../../app.config";

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
    constructor(
        private storage: Storage,
    ) {
    }


    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const method = req.method;
        const body = req.body;
        const accessToken = this.storage.get(TOKEN);
        const headers = {};
        let url = SERVER_PATH + req.url;

        if (accessToken) {
            headers[TOKEN] = accessToken;
        }

        if (method === 'GET' && body) {
            url = url + '?' + this.formData(body);
        }

        const newReq = req.clone({
            url: url,
            setHeaders: headers
        });
        return next.handle(newReq);
    }


    private formData(data: Object) {
        return Object.keys(data).map(function (key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
        }).join('&');
    }


}